<template>
  <!-- 表格卡片 -->
  <a-card size="small" :bordered="false" :hoverable="true" :scroll="{ x: 1500 }">
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <a-row :gutter="16">
          <a-col :span="10"> <a-input v-model:value="queryForm.key" placeholder="关键字查询" /></a-col>
          <a-col :span="5">
            <a-button type="primary" @click="getInitDateFind"><SearchOutlined />查询</a-button></a-col
          >
          <a-col :span="2">
            <a-button @click="getRemase"><ReloadOutlined />重置</a-button></a-col
          >
        </a-row>
      </div>
      <div class="smart-table-setting-block">
        <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.BUSINESS.OA.ENTERPRISE" :refresh="getInitDate" />
      </div>
    </a-row>
    <a-table
      size="small"
      :dataSource="tableData"
      :columns="columns"
      :row-key="(record) => record.blfinancprojectid"
      :pagination="false"
      :loading="tableLoading"
      bordered
      @change="handleTableChange"
    >
      <template #bodyCell="{ column, record, text }">
        <template v-if="column.dataIndex === 'blprojectname'" title="项目名称">
          <div class="smart-table-operate">
            <span style="color: #1677ff" @click="getAddInstantly(1, record.blfinancprojectid)">{{ record.blprojectname }}</span>
          </div>
        </template>
        <template v-if="column.dataIndex === 'action'" title="操作">
          <div class="smart-table-operate">
            <a-space>
              <a-popconfirm
                title="确认收到审核后的学院申请表?"
                ok-text="确定"
                cancel-text="取消"
                @confirm="confirm(record.blfinancprojectid)"
                v-if="record.blauditstate == 2"
              >
                <span style="color: #66a5fd" v-if="record.blauditstate == 2">确认</span>
              </a-popconfirm>
              <span style="color: #66a5fd" v-if="record.blauditstate == 4" @click="showModal(record.blfinancprojectid)">上传申报书</span>
              <span style="color: #66a5fd" v-if="record.blauditstate == 3" @click="showModalCode(record.blfinancprojectid)">上传项目二维码</span>
              <span style="color: #66a5fd" v-if="record.blauditstate == 5" @click="getAddInstantly(2, record.blprojectnum)">查看协议</span>
            </a-space>
          </div>
        </template>
        <template v-if="column.dataIndex === 'blauditstate'" title="申请状态">
          <div class="smart-table-operate">
            <span v-if="record.blauditstate == 0">资料已填写等待审核</span>
            <span v-if="record.blauditstate == 1">基金会审核</span>
            <span v-if="record.blauditstate == -1">基金会审核未通过</span>
            <span v-if="record.blauditstate == 2">基金会审核通过,等待递交纸质件</span>
            <span v-if="record.blauditstate == 3 || record.blauditstate == 4">收到纸质件等待基金确认</span>
            <span v-if="record.blauditstate == 5">申报成功</span>
          </div>
        </template>
      </template>
    </a-table>
    <!-- 分页-->
    <div class="smart-query-table-page">
      <a-pagination
        showSizeChanger
        showQuickJumper
        show-less-items
        :pageSizeOptions="PAGE_SIZE_OPTIONS"
        :defaultPageSize="queryForm.limit"
        v-model:current="queryForm.page"
        v-model:pageSize="queryForm.limit"
        :total="total"
        @change="getInitDate"
        @showSizeChange="getInitDate"
        :show-total="(total) => `共${total}条`"
      />
    </div>
  </a-card>
  <!-- 上传申报书 -->
  <a-modal v-model:open="open" title="上传申报书" width="600px">
    <div style="padding: 20px 0px">
      <a-upload-dragger
        v-model:fileList="fileList"
        name="file"
        @change="handleChange"
        :max-count="1"
        :before-upload="beforeUpload"
        :accept="'.pdf, .doc, .docx,image/jpg,image/jpeg,image/png'"
        :customRequest="customUploadBook"
      >
        <p class="ant-upload-drag-icon">
          <inbox-outlined></inbox-outlined>
        </p>
        <p class="ant-upload-text">单击或者拖动文件到此区域进行上传</p>
        <p class="ant-upload-hint">仅支持上传doc/docx/pdf/jepg/jpg/png</p>
      </a-upload-dragger>
    </div>
    <template #footer>
      <a-button key="back" @click="handleCancel">取消</a-button>
      <a-button key="submit" type="primary" @click="handleOk" :disabled="fileList.length ? false : true">提交</a-button>
    </template>
  </a-modal>
  <!-- 上传code二维码 -->
  <a-modal v-model:open="openCode" title="上传二维码" @ok="handleOkCode" width="600px">
    <div style="padding: 20px 0px">
      <a-upload-dragger
        v-model:fileList="fileListCode"
        accept="image/jpg,image/jpeg,image/png"
        name="file"
        :max-count="1"
        :before-upload="beforeUploadCode"
        @change="handleChangeCode"
        :customRequest="customUpload"
      >
        <p class="ant-upload-drag-icon">
          <inbox-outlined></inbox-outlined>
        </p>
        <p class="ant-upload-text">单击或者拖动文件到此区域进行上传</p>
        <p class="ant-upload-hint">仅支持上传jpg/png/jpeg格式文件</p>
      </a-upload-dragger>
    </div>
    <template #footer>
      <a-button key="back" @click="handleCancel">取消</a-button>
      <a-button key="submit" type="primary" @click="handleOkCode" :disabled="fileListCode.length ? false : true">提交</a-button>
    </template>
  </a-modal>
</template>
<script setup>
  import { reactive, ref, onMounted, defineEmits } from 'vue';
  import { message, Modal } from 'ant-design-vue';
  import { SmartLoading } from '/@/components/framework/smart-loading';
  import { Fundingapproval } from '../../../../api/Fundingapproval/Fundingapproval-api';
  import { PAGE_SIZE, PAGE_SIZE_OPTIONS } from '/@/constants/common-const';
  import TableOperator from '/@/components/support/table-operator/index.vue';
  import { TABLE_ID_CONST } from '/@/constants/support/table-id-const';
  import { smartSentry } from '/@/lib/smart-sentry';
  //--------------------------- 表格 列 ---------------------------
  const columns = ref([
    {
      title: '项目名称',
      dataIndex: 'blprojectname',
      align: 'center',
      width: 150,
    },
    {
      title: '项目申请时间',
      dataIndex: 'bldate',
      align: 'center',
      sorter: (a, b) => {
        let aTimeString = a.bldate;
        let bTimeString = b.bldate;
        aTimeString = aTimeString.replace(/-/g, '/');
        bTimeString = bTimeString.replace(/-/g, '/');
        let aTime = new Date(aTimeString).getTime();
        let bTime = new Date(bTimeString).getTime();
        return bTime - aTime;
      },
    },
    {
      title: '申请单位',
      dataIndex: 'blsubject',
      align: 'center',
    },
    {
      title: '联系人',
      dataIndex: 'bllinker',
      align: 'center',
    },
    {
      title: '联系方式',
      dataIndex: 'bllinktel',
      align: 'center',
    },
    {
      title: '申请状态',
      dataIndex: 'blauditstate',
      align: 'center',
    },
    {
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
      align: 'center',
      width: 300,
    },
  ]);
  const queryFormState = {
    page: 1,
    limit: PAGE_SIZE,
  };
  const queryForm = reactive({ ...queryFormState });
  const tableLoading = ref(false);
  const tableData = ref([]);
  const total = ref(0);
  // 表格初始化
  function getInitDateFind() {
    message.success('查询成功');
    getInitDate();
  }
  //重置
  function getRemase() {
    message.success('重置成功');
    queryForm.key = '';
    getInitDate();
  }
  async function getInitDate() {
    try {
      let res = await Fundingapproval.FundAuditval(queryForm);
      console.log(res, '初始化');
      tableData.value = res.data.list;
      total.value = res.data.totalCount;
    } catch (error) {
      smartSentry.captureError(error);
    }
  }
  //确认
  const confirm = (id) => {
    let obj = {
      id: id,
      status: 3,
    };
    Fundingapproval.updateStatus(obj)
      .then((res) => {
        console.log(res, '提交状态');
        message.success('确认成功');
        getInitDate();
      })
      .catch((error) => {
        smartSentry.captureError(error);
      });
  };
  //------------------------------上传申报书模态框--------------------------------------------
  const open = ref(false);
  const bookId = ref();
  const fileList = ref([]);
  const bookFile = ref([]);
  const showModal = (id) => {
    bookId.value = id;
    open.value = true;
  };

  //上传申报书文件上传模块
  const handleChange = (data) => {
    console.log('进入errror', data.file.status);
    if (data.file.status == 'uploading') {
      //改变上传的状态显示图片
      data.file.status = 'done';
      fileList.value = [...data.fileList];
    } else if (data.file.status == 'removed') {
      //如果状态为remove就删除
      fileList.value = data.fileList;
      bookFile.value = '';
    } else if (!data.file.status) {
      fileList.value = [];
    }
  };
  //对上传申报书做校验
  function beforeUpload(file) {
    let fileType = file.name.split('.');
    const fileDate = fileType.slice(-1);
    console.log(['doc', 'docx', 'pdf', 'jpeg', 'jpg', 'png'].indexOf(fileDate[0]));

    if (['doc', 'docx', 'pdf', 'jpeg', 'jpg', 'png'].indexOf(fileDate[0]) < 0) {
      message.error('仅支持文件格式：.doc、.docx、pdf、jpeg、jpg、png格式附件!');
      return false;
    }
    const isLt200M = file.size / 1024 / 1024 < 100;
    if (!isLt200M) {
      message.error('附件大小不能超过100M!');
      return false;
    }
    return true;
  }
  function customUploadBook(file) {
    bookFile.value = file.file;
  }
  //申报书上传方法
  const handleOk = async (e) => {
    open.value = false;
    try {
      let formData = new FormData();
      formData.append('file', bookFile.value);
      let res = await Fundingapproval.updateLoadCode(bookId.value, formData);
      open.value = false;
      fileList.value = [];
      bookFile.value = '';
      message.success('上传成功');
      getInitDate();
    } catch (error) {
      fileList.value = [];
      bookFile.value = '';
      smartSentry.captureError(error);
    }
  };
  // -----------------------------------------------上传二维码模态框----------------------------------------------
  const openCode = ref(false);
  const codeId = ref();
  const fileListCode = ref([]);
  const CodeImg = ref();
  const showModalCode = (id) => {
    openCode.value = true;
    codeId.value = id;
  };
  const handleCancel = () => {
    openCode.value = false;
    open.value = false;
  };
  //上传二维码文件上传模块
  function beforeUploadCode(file) {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('只能上传jpg/png格式的图片');
      return false; // 阻止文件上传
    }
    const isLt2M = file.size / 1024 / 1024 < 10;
    if (!isLt2M) {
      message.error('图片不得大于10MB!');
      return false; // 阻止文件上传
    }
    return isLt2M && isJpgOrPng;
  }
  function handleChangeCode(data) {
    console.log('进入errror', data.file.status);
    if (data.file.status == 'uploading') {
      //改变上传的状态显示图片
      data.file.status = 'done';
      fileListCode.value = [...data.fileList];
    } else if (data.file.status == 'removed') {
      //如果状态为remove就删除
      fileListCode.value = data.fileList;
      CodeImg.value = '';
    } else if (!data.file.status) {
      fileListCode.value = [];
    }
  }
  //自定义上传
  function customUpload(file) {
    CodeImg.value = file.file;
  }
  //二维码删上传方法
  const handleOkCode = async (e) => {
    try {
      let formData = new FormData();
      formData.append('file', CodeImg.value);
      let res = await Fundingapproval.updateLoadCode(codeId.value, formData);
      openCode.value = false;
      fileListCode.value = [];
      CodeImg.value = '';
      message.success('上传成功');
      getInitDate();
    } catch (error) {
      fileListCode.value = [];
      CodeImg.value = '';
      smartSentry.captureError(error);
    }
  };
  //返回立项申请表格页面
  const emit = defineEmits();
  const getAddInstantly = (e, id) => {
    let obj = {
      type: e,
      id: id,
    };
    emit('getBlack', obj);
  };

  onMounted(() => {
    getInitDate();
  });
</script>
